<template>
  <div class="app-container">
    <el-container>
      <el-header >
        <el-row :gutter="5" style="padding-top: 15px">
          <!--           左     -->
          <el-col :span="8" align="left">
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAdd"
                  v-hasPermi="['jbxx:brand:add']"
                >新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="success"
                  plain
                  icon="el-icon-edit"
                  size="mini"
                  :disabled="single"
                  @click="handleUpdate"
                  v-hasPermi="['jbxx:brand:edit']"
                >修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  plain
                  icon="el-icon-delete"
                  size="mini"
                  :disabled="multiple"
                  @click="handleDelete"
                  v-hasPermi="['jbxx:brand:remove']"
                >删除</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="warning"
                  plain
                  icon="el-icon-download"
                  size="mini"
                  @click="handleExport"
                  v-hasPermi="['jbxx:brand:export']"
                >导出</el-button>
              </el-col>
            </el-row>
          </el-col>
          <!--           右     -->
          <el-col :span="16" align="right" >
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>

              <el-form-item  prop="isStatus">
                <el-select v-model="queryParams.isStatus" placeholder="按启用的状态筛选" clearable>
                  <el-option value="1" label="启用" key="1"></el-option>
                  <el-option value="0" label="停用" key="0"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item prop="ppName">
                <el-input
                  v-model="queryParams.ppName"
                  placeholder="请输入品牌名称"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </el-header>

      <el-main>
        <el-table border stripe v-loading="loading" :data="brandList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" align="center" type="index" :index="indexMethod" />
          <el-table-column label="产品品牌编码" align="center" prop="cptypeCode" />
          <el-table-column label="品牌名称" align="center" prop="ppName" />
          <el-table-column label="品牌简称" align="center" prop="ppEasy" />
          <el-table-column label="英文名称" align="center" prop="usaName" />
          <el-table-column label="关联客商" align="center" prop="merchantsName" >
            <template #default="scope">
              <!-- 使用v-for结合文本显示 -->
              <span v-for="(ksValue, index) in scope.row.ksMerchantsList" :key="index">
                {{ index > 0 ? '| ' : '' }}{{ ksValue.merchantsName }}
             </span>
            </template>
          </el-table-column>
          <el-table-column label="启用" align="center" key="isStatus" v-if="columns[0].visible">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.isStatus"
                active-value="true"
                inactive-value="false"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['jbxx:brand:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['jbxx:brand:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>

      <el-footer>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-footer>
    </el-container>



    <!-- 添加或修改产品品牌对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="品牌名称" prop="ppName">
              <el-input v-model="form.ppName" placeholder="请输入品牌名称" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="品牌简称" prop="ppEasy">
              <el-input v-model="form.ppEasy" placeholder="请输入品牌简称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="英文名称" prop="usaName">
              <el-input v-model="form.usaName" placeholder="请输入英文名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="center">关联客商信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddKsMerchants">{{buttonText }}</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteKsMerchants">删除</el-button>
          </el-col>
        </el-row>
        <el-table border stripe :data="ksMerchantsList" :row-class-name="rowKsMerchantsIndex" @selection-change="handleKsMerchantsSelectionChange" ref="ksMerchants">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="100"/>
          <el-table-column label="客商名称" prop="merchantsName">
            <template slot-scope="scope">
              <el-input v-model="scope.row.merchantsName" placeholder="请输入客商名称" disabled/>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!--     选择客商    -->
    <el-dialog title="选择客商" :visible.sync="dialogTableVisibleHead">

      <el-form :model="queryParamsTwo" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

        <el-row>
          <el-col :span="8">
            <div>
              <el-form-item  prop="merchantsName">
                <el-input
                  v-model="queryParamsTwo.merchantsName"
                  placeholder="关键字筛选"
                  clearable
                  @keyup.enter.native="handleQueryChangeFactory"
                />
              </el-form-item>
            </div>
          </el-col>

          <el-col :span="16">
            <div align="right">
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryChangeFactory" style="background-color: rgba(0,176,192);color: #FFFFFF">查询</el-button>
              </el-form-item>
            </div>
          </el-col>
        </el-row>

      </el-form>

      <el-table border stripe :data="ksMerchantsListType" ref="multipleTableFactory" @selection-change="handleSelectionChangeFactory">
        <el-table-column type="selection" width="55" align="center"  />
        <el-table-column property="merchantsName" label="客商名称"></el-table-column>
        <el-table-column property="merchantsAbbreviation" label="客商简称"></el-table-column>
        <el-table-column label="客商等级" align="center" prop="ksLevelCode">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.ks_level" :value="scope.row.ksLevelCode"/>
          </template>
        </el-table-column>
        <el-table-column label="所属行业" align="center" prop="ksIndustryCode">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.ks_industry" :value="scope.row.ksIndustryCode"/>
          </template>
        </el-table-column>
      </el-table>

      <el-row :gutter="5">
        <el-col :span="24" align="right">
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer" align="center" style="padding-top: 20px">
        <el-button @click="cancelFactory" style="background-color: rgba(0,176,192);color: #FFFFFF">取 消</el-button>
        <el-button type="primary" @click="submitFormFactory">保 存</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { listBrand, getBrand, delBrand, addBrand, updateBrand,updateAttributeIsStatus } from "@/api/jbxx/brand";
import {listMerchants} from "@/api/jbxx/merchants";


export default {
  name: "Brand",
  dicts: ['ks_level', 'ks_attributes', 'ks_classification', 'ks_industry'],
  data() {
    return {
      // 遮罩层
      loading: true,
      buttonText: '添加',
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedKsMerchants: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品品牌表格数据
      brandList: [],
      // 客商管理表格数据
      ksMerchantsList: [],
      //客商关联选择表格数据
      ksMerchantsListType: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ppName: null,
        isStatus: null,
        merchantsName:null
      },
      queryParamsTwo: {
        pageNum: 1,
        pageSize: 10,
        ppName: null,
        isStatus: null,
        merchantsName:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        ppName: [
          { required: true, message: "品牌名称不能为空", trigger: "blur" }
        ],
        ppEasy: [
          { required: true, message: "品牌简称不能为空", trigger: "blur" }
        ],
        usaName: [
          { required: true, message: "英文名称不能为空", trigger: "blur" }
        ],
      },
      dialogTableVisibleHead:null,
      selectedRow:null,
      // 列信息
      columns: [
        { key: 0, label: `启用`, visible: true },
      ],
    };
  },
  created() {
    this.getList();
    this.getListMerchants();
  },
  methods: {
    /** 查询产品品牌列表 */
    getList() {
      this.loading = true;
      listBrand(this.queryParams).then(response => {

        for (let i = 0; i < response.rows.length; i++) {
          response.rows[i].isStatus = response.rows[i].isStatus === 1 ? 'true' : 'false';
        }

        this.brandList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 查询客商管理列表 */
    getListMerchants() {
      listMerchants(this.queryParamsTwo).then(response => {
        this.ksMerchantsListType = response.rows;
        this.total = response.total;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        cptypeCode: null,
        ppName: null,
        ppEasy: null,
        usaName: null,
        ksCode: null,
        isUse: null,
        isDelete: null,
        isStatus: null
      };
      this.ksMerchantsList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.cptypeCode)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增品牌";
      this.queryParamsTwo.merchantsName = null;
      this.selectedRow = null;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const cptypeCode = row.cptypeCode || this.ids
      getBrand(cptypeCode).then(response => {
        this.form = response.data;
        this.ksMerchantsList = response.data.ksMerchantsList;
        this.queryParamsTwo.merchantsName = null;
        this.open = true;
        this.title = "编辑品牌";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {

          if (this.ksMerchantsList.length==0){
            this.$message.error("关联客商不能为空，请添加！")
            return false;
          }

          this.form.ksMerchantsList = this.ksMerchantsList;
          if (this.form.cptypeCode != null) {
            updateBrand(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBrand(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const cptypeCodes = row.cptypeCode || this.ids;
      this.$modal.confirm('是否确认删除产品品牌编号为"' + cptypeCodes + '"的数据项？').then(function() {
        return delBrand(cptypeCodes);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 客商管理序号 */
    rowKsMerchantsIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },

    /** 客商管理添加按钮操作 */
    handleAddKsMerchants() {
      this.open = false;
      this.dialogTableVisibleHead = true;

      this.$nextTick(() => {
        if (this.ksMerchantsList != null) {
          this.selectRowById(this.ksMerchantsList);
        }
      });
    },

    /** 产品分类修改默认选择 */
    selectRowById(ksMerchantsList) {
      // 确保sxAttributeValueListCpType是数组
      if (!Array.isArray(ksMerchantsList)) {
        console.error('Expected an array for sxAttributeValueListCpType');
        return;
      }

      // 初始化一个空数组用于存储需要选中的行
      let rowsToSelect = [];

      // 遍历sxAttributeValueListCpType数组
      for (let i = 0; i < ksMerchantsList.length; i++) {
        const merchantsName = ksMerchantsList[i].merchantsName;

        // 再次遍历this.sxAttributeValueCpflList数组
        for (let j = 0; j < this.ksMerchantsListType.length; j++) {
          const item = this.ksMerchantsListType[j];

          // 检查当前item的cpflName是否与sxAttributeValueListCpType中的cpflName匹配
          if (item.merchantsName === merchantsName) {
            // 如果匹配，则将item添加到rowsToSelect数组中
            rowsToSelect.push(item);
            break; // 找到匹配项后跳出内层循环
          }
        }
      }

      if (rowsToSelect.length > 0) {
        for (let i = 0; i < rowsToSelect.length; i++) {
          this.$refs.multipleTableFactory.toggleRowSelection(rowsToSelect[i]);
          this.selectedRow = rowsToSelect[i];
        }
      }
    },

    /** 客商管理删除按钮操作 */
    handleDeleteKsMerchants() {
      if (this.checkedKsMerchants.length == 0) {
        this.$modal.msgError("请先选择要删除的客商管理数据");
      } else {
        const ksMerchantsList = this.ksMerchantsList;
        const checkedKsMerchants = this.checkedKsMerchants;
        this.ksMerchantsList = ksMerchantsList.filter(function(item) {
          return checkedKsMerchants.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleKsMerchantsSelectionChange(selection) {
      this.checkedKsMerchants = selection.map(item => item.index)
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('jbxx/brand/export', {
        ...this.queryParams
      }, `brand_${new Date().getTime()}.xlsx`)
    },

    /**产品分类取消*/
    cancelFactory() {
      this.dialogTableVisibleHead=false;
      this.open = true;
      this.$refs.multipleTableFactory.clearSelection();
      if (this.title=="新增品牌"){
        if (this.ksMerchantsList != null){
          this.selectedRow = null;
          this.ksMerchantsList=undefined
        }
      }
    },

    /** 产品分类提交 */
    submitFormFactory(){
      this.dialogTableVisibleHead = false;
      this.open = true;
    },

    /** 客商多选框选中数据 */
    handleSelectionChangeFactory(selection) {
      if (selection.length > 1) {
        // 如果选择了超过一行，则取消选择
        this.$refs.multipleTableFactory.clearSelection();
        // 保留最后一行被选中
        this.$refs.multipleTableFactory.toggleRowSelection(selection[1], true);
      } else {
        // 如果只有一行被选中，则更新selectedRow
        this.selectedRow = selection.length ? selection[0] : null;
      }

      this.ids = selection.map(item => item.name)
      this.single = selection.length!==1
      this.multiple = !selection.length

      if (this.title == "新增品牌") {

        const updatedSelection = this.$refs.multipleTableFactory.selection;
        this.ksMerchantsList = updatedSelection;
      } else {
        for (let i = 0; i < selection.length; i++) {
          for (let j = 0; j < this.ksMerchantsList.length; j++) {
            this.ksMerchantsList[j].merchantsName = selection[i].merchantsName;
            this.ksMerchantsList[j].ksCode = selection[i].ksCode;
          }
        }
      }
    },

    /** 产品分类搜索按钮操作 */
    handleQueryChangeFactory() {
      this.queryParamsTwo.pageNum = 1;
      this.getListMerchants();
    },



    /** 产品属性状态修改 */
    handleStatusChange(row) {

      console.log(row)
      let text = row.isStatus === "true" ? "启用" : "停用";

      let isStatus = row.isStatus === "true" ? "1" : "0";
      this.$modal.confirm('确认要"' + text + '""' + row.ppName + '"用户吗？').then(function()
      {

        return updateAttributeIsStatus(row.cptypeCode, isStatus);

      }).then(() => {

        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {

        row.isStatus = row.isStatus === "true" ? "1" : "0";
      });
    },

    /** 属性序号 */
    indexMethod(index) {
      return index + 1 ;
    },

  }
};
</script>
<style>
/*弹出框圆角边框样式*/
.el-dialog{
  border-radius: 20px;
}

.el-message--warning {
  background-color: #fff3cd; /* 警告消息背景色 */
  color: #856f00; /* 警告消息文本颜色 */
  border-color: #ffe68a; /* 警告消息边框颜色 */
}

.el-message__content {
  color: red; /* 修改警告消息内容的颜色 */
}
</style>
